var dl, cookie, mainSku, main, deta, all, select, mouch, num, footAll, btn, qk,left,cart,ydl,shop,right,dl,user,overs,dls;
import StepNumber from "../js/StepNumber.js"

init()
async function init() {
    var response = await fetch("http://localhost:3860/shoppinglist")
    var data = await response.json();
    init5(data);

}
function init5(data) {

    deta = data.map(function (t) {
        return {
            pid: t.pid,
            ck: true,
            img: t.img,
            txt: t.txt,
            price: t.price,
            num: t.num,
            total: t.price * t.num,
            remove: "remove"
        }
    })
    cookie = localStorage
    dls = document.querySelector(".kong-dl");
    main = document.querySelector(".mains")
    mainSku = document.querySelector(".mainSku")
    all = document.querySelector(".all")
    num = document.querySelector(".num").querySelector("span")
    select = document.querySelector(".all");
    mouch = document.querySelector(".sum-box").querySelector("span")
    footAll = document.querySelector(".footAll")
    btn = document.querySelector(".jiesuan")
    qk = document.querySelector(".q-k")
    left=document.querySelector(".btn").querySelector(".left")
    cart=document.querySelector(".cart");
    ydl=document.querySelector(".ydl")
    shop=document.querySelector(".shop")
    right=document.querySelector(".right");
    dl=document.querySelector(".dl");
    user=document.querySelector(".user")
    overs=document.querySelector(".over");
    
    overs.addEventListener("click",over)
    document.addEventListener("scroll",scrollHandler)
    footAll.addEventListener("click", checkedHandler)
    all.addEventListener("click", checkedHandler)
    btn.addEventListener("click", clickHandler);
    qk.addEventListener("click", clicHandler,);
    updateTable()
    cookieHandler(cookie)
}
function clicHandler() {
    if(deta.length==0){
        alert("您没有商品，快去逛逛吧")
    }else{
        alert(`已清空，快去逛逛吧`)
        QKHandler()
    }
   
}

function clickHandler() {
    if (mouch.innerHTML == "0") {
        alert("您没有商品，快去逛逛吧")
    } else {
        alert(`购买成功,共消费${mouch.innerHTML}元`)
        QKHandler()
    }

}

function QKHandler(e) {


    var xhr = new XMLHttpRequest();
    xhr.addEventListener("load", loadHandler);
    xhr.open("POST", "http://localhost:3860/qingkon");
    xhr.send(JSON.stringify())
    function loadHandler() {
        var bool = JSON.parse(xhr.response)
        if (bool.msg === "已清空") {
            init()
        }
    }
}

function updateTable() {
    main.innerHTML = "";
    var elem = document.createDocumentFragment();
    for (var i = 0; i < deta.length; i++) {
        var clear = document.createElement("div")
        clear.className = "clear"
        for (var key in deta[i]) {
            if (key === "id") continue;
            var divs = document.createElement("div");
            createTdContent(divs, key, deta[i])
            clear.appendChild(divs);
        }
        elem.appendChild(clear);
    }
    select.checked = deta.every(t => t.ck)
    footAll.checked = deta.every(t => t.ck)
    mouch.innerHTML = deta.reduce((v, t) => {
        if (t.ck) return v + Number(t.total);
        return v;
    }, 0)
    num.innerHTML = deta.length
    main.appendChild(elem)
}
function checkedHandler() {
    if (this == all) {
        deta.forEach(t => t.ck = all.checked)
    } else if (this == footAll) {
        deta.forEach(t => t.ck = footAll.checked)
    } else {
        deta.forEach(t => {
            if (t.pid === this.pid) {
                t.ck = this.checked;
            }
        })
    }
    updateTable()
}

function createTdContent(divs, key, goods) {
    switch (key) {
        case "ck":
            var cks = document.createElement("input");
            cks.type = "checkbox";
            cks.pid = goods.pid
            cks.checked = goods.ck
            divs.appendChild(cks);
            divs.className = "check";
            cks.addEventListener("click", checkedHandler)
            break;
        case "img":
            var img = new Image();
            img.src = goods.img;
            divs.appendChild(img);
            divs.className = "imgs";
            break;
        case "price":
            var p = document.createElement("p");
            p.innerHTML = `
            ￥<span>${goods.price}</span>
            `
            divs.appendChild(p)
            p.parentNode.className = "danjia"
            break;
        case "num":
            var step = new StepNumber();
            step.appendTo(divs)
            step.pid = goods.pid
            step.setStep(goods.num);
            divs.className = "jisuanqi"
            break;

        case "txt":
            var h3 = document.createElement("h3");
            h3.innerHTML = goods.txt;
            divs.appendChild(h3)
            divs.className = "text";
            break;
        case "total":
            var ps = document.createElement("p");
            ps.innerHTML = `
                ￥<span>${goods.total}</span>
                `
            divs.appendChild(ps)
            ps.parentNode.className = "jiage"
            break;
        case "remove":
            var button = document.createElement("button");
            button.innerHTML = "删除"
            button.pid = goods.pid
            divs.appendChild(button);
            divs.className = "caozuo"
            button.addEventListener("click", removeHandler);
            break;

    }
}


// 修改数据
function XGHandler(step, pid) {
    var pid = Number(pid)
    var arr = { step: step, pid: pid };
    var xhr = new XMLHttpRequest();
    xhr.addEventListener("load", Xhandler);
    xhr.open("POST", "http://localhost:3860/xiugai");
    xhr.send(JSON.stringify(arr))
    function Xhandler() {
        var bools = JSON.parse(xhr.response);
        if (bools.msg === "商品数量修改成功") {
            init()
        }
    }
}



// 删除
function removeHandler(e) {
    var xhr = new XMLHttpRequest();
    xhr.addEventListener("load", loadHandler);
    xhr.open("POST", "http://localhost:3860/remove");
    xhr.send(JSON.stringify(this.pid))
    function loadHandler() {
        var bool = JSON.parse(xhr.response)
        if (bool.msg === "商品删除成功") {
            init()
        }
    }
}






function cookieHandler(cookie) {
      
    if (cookie.bool) {
        user.innerHTML=cookie.input
        right.style.display="block"
       
        ydl.style.display="block"
        if(deta.length==0){
            shop.innerHTML="您的购物车空空如也，赶快选购吧～"
            dl.style.display = "none"
            dls.style.display="block"
            left.style.display="none"
        }else{
            dls.style.display = "none"
            
        }
        
    } else {
        right.style.display="none"
        dls.style.display="block"
        deta.length=0
        dl.style.display = "block"
        left.style.display="block"
        ydl.style.display="none"
        mouch.innerHTML=0
        num.innerHTML=0
        shop.innerHTML="欢迎光临,请登录！！"
    }
   
}
function over(){
    cookie.removeItem("bool")
    cookie.removeItem("input")
    init()
}

function scrollHandler(){
    if(document.documentElement.scrollTop>300){
        cart.style.position="fixed"
    }else{
        cart.style.position="static"
    }
}
export default {
    XGHandler
}
